package com.exec;

import com.tycmc.util.RedisUtil;
import com.util.DateUtil;
import com.util.DruidUtil;
import com.util.PropertiesUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import ty.pub.TransPacket;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EleDriveFltController {
    /*
    *电驱动故障逻辑处理
     */
    public  static String execEleDriveFlt(com.tycmc.bean.InputObject inputObject)  {
        //获取电驱动故障11个工况编号
        String EleDriveFltNumbers = PropertiesUtil.getStringPro("EleDriveFltNumber");
        //切割字符串获取各个工况编号
        String[] EleDriveFltCode = EleDriveFltNumbers.split(",");
        //信息生成时间编号
        String msgTimeNumber=PropertiesUtil.getStringPro("MsgTimeNumber");
        String EleDriveFlt=PropertiesUtil.getStringPro("EleDriveFlt");

        //获取kafka拉取到的工况
        TransPacket transPacket = inputObject.getTransPacket();
        //获取基础数据
        Map<String,String> baseInfo = transPacket.getBaseInfoMap();
        //基础时间
        Long baseMsgTime = MapUtils.getLong(baseInfo,msgTimeNumber);
        String msgTime = DateUtil.getStrTime(baseMsgTime,0L);
        //获取设备ID
        String vclId=transPacket.getDeviceId();
        //去掉设备ID的前缀
        vclId=vclId.substring(4,vclId.length());
        //获取工况数据
        Map<String,Map<Long,String>> workStatusMap = transPacket.getWorkStatusMap();
        //用来保存从kafka拉取到的数据
        Map<String,String> kfkFltMap = new HashMap<String,String>();
        //循环获取11个工况的数据
        boolean flag = false;//判断本次是否有电驱动故障过来
        for(int i=0;i<EleDriveFltCode.length;i++){
            Map<Long,String> mmap = workStatusMap.get(EleDriveFltCode[i]);
            if(MapUtils.isEmpty(mmap)){
                continue;
            }
            flag = true;
                //循环mmap获取时间key和值value并判断当前拉取到的数据是否是0（如果是0则去掉）
                for(long key : mmap.keySet()){
                    String value = mmap.get(key);
                    if(!"0".equals(value)){
                        if(!kfkFltMap.containsKey(value)){
                            //如果该次故障集合已经存在该故障，则不再重复保存
                            kfkFltMap.put(value,msgTime);
                        }
                    }
                }

        }
        if(flag==true) {
            List<String> sqlList = new ArrayList<String>();
            //获取信息生成时间数据集合
            Map<String,Object>mapStatic=inputObject.getCacheMap();
            String theVclmsgTime=MapUtils.getString(mapStatic,vclId+"_"+EleDriveFlt);
            //如果为空，直接存入缓存map中
            if(StringUtils.isBlank(theVclmsgTime)){
                mapStatic.put(vclId+"_"+EleDriveFlt,msgTime);
                sqlList.add(" insert into  CacheKZExecTable(CKZET_VclId,CKZET_LastMsgTime,CKZET_InsertTime,CKZET_Type)values('"+vclId+"','"+msgTime+"',now(),"+EleDriveFlt+")  " +
                        "ON DUPLICATE KEY UPDATE CKZET_LastMsgTime='"+msgTime+"',CKZET_InsertTime=now()");
            }else{//如果不为空
                //上下时间比较
                long lastVclmsgTime=Long.valueOf(DateUtil.getLongTime(theVclmsgTime));
                if(baseMsgTime>=lastVclmsgTime){
                    mapStatic.put(vclId+"_"+EleDriveFlt,msgTime);
                    sqlList.add(" insert into  CacheKZExecTable(CKZET_VclId,CKZET_LastMsgTime,CKZET_InsertTime,CKZET_Type)values('"+vclId+"','"+msgTime+"',now(),"+EleDriveFlt+")  " +
                            "ON DUPLICATE KEY UPDATE CKZET_LastMsgTime='"+msgTime+"',CKZET_InsertTime=now()");
                }else{
                    //缓存数据
                    return null;
                }
            }
            //获取该设备在redis中存储的工况信息
            //拼接设备故障key
            String redisKey = PropertiesUtil.getStringPro("RedisEleDriveFlt") + vclId;
            //首先判断该设备故障信息是否存在
            Jedis jedis = RedisUtil.getJedis();
            Transaction tx = jedis.multi();//开启事务
            if (RedisUtil.exist(redisKey)) {
                //该设备故障信息存在于redis,判断kafka获取的故障信息是否为空
                if (kfkFltMap.isEmpty()) {
                    //为空（将所有现行故障全部解除，redis中删掉，现行故障表删掉，更新故障月表）
                    Map<String, String> happeningFlt = new HashMap<String, String>();
                    happeningFlt = RedisUtil.hgetAll(redisKey);
                    for (String fltCode : happeningFlt.keySet()) {
                        String fltTime = MapUtils.getString(happeningFlt, fltCode);
                        String FltTableN = fltTime.substring(0, 7).replace("-", "");
                        //删除redis相关故障
                        tx.hdel(redisKey, fltCode);
                        //删除现行故障表
                        sqlList.add("DELETE FROM Msg_Flt_Happening WHERE MsgFH_Code=" + fltCode + "");
                        //更新故障月表(解除时间用该次卡夫卡取出的时间)
                        sqlList.add("UPDATE Msg_FaultAlarm_" + FltTableN + " SET MsgFA_Release='" + msgTime + "',MsgFA_State=2 WHERE MsgFA_Code=" + fltCode + "");
                    }
                } else {
                    //不为空（两边都不为空进一步判断）redis一边多出来的是解除，kakfka一边多出来的是新增，两边交集的不动
                    Map<String, String> redisFltMap = new HashMap<String, String>();
                    redisFltMap = RedisUtil.hgetAll(redisKey);
                    //先处理解除的故障
                    for (String rFltCode : redisFltMap.keySet()) {
                        if (!kfkFltMap.containsKey(rFltCode)) {
                            String fltTime = MapUtils.getString(redisFltMap, rFltCode);
                            String FltTableN = fltTime.substring(0, 7).replace("-", "");
                            //将该故障解除
                            //删除redis相关故障
                            tx.hdel(redisKey, rFltCode);
                            //删除现行故障表
                            sqlList.add("DELETE FROM Msg_Flt_Happening WHERE MsgFH_Code=" + rFltCode + "");
                            //更新故障月表(解除时间用该次卡夫卡取出的时间)
                            sqlList.add("UPDATE Msg_FaultAlarm_" + FltTableN + " SET MsgFA_Release='" + msgTime + "',MsgFA_State=2 WHERE MsgFA_Code=" + rFltCode + "");
                        }
                    }
                    //处理新增的故障
                    for (String kFltCode : kfkFltMap.keySet()) {
                        if (!redisFltMap.containsKey(kFltCode)) {
                            String fltTime = MapUtils.getString(kfkFltMap, kFltCode);
                            String FltTableN = fltTime.substring(0, 7).replace("-", "");
                            //新增故障
                            Map<String, String> mmap = new HashMap<String, String>();
                            mmap.put(kFltCode, fltTime);
                            //将故障存入redis
                            tx.hmset(redisKey, mmap);
                            //新增现行故障
                            sqlList.add("INSERT INTO Msg_Flt_Happening(MsgFH_Vcl_ID,MsgFH_MsgTime,MsgFH_FaultType,MsgFH_Code) VALUES (" + vclId + ",'" + fltTime + "',2," + kFltCode + ")");
                            //新增故障月表
                            sqlList.add("INSERT INTO Msg_FaultAlarm_" + FltTableN + "(MsgFA_Vcl_ID,MsgFA_MsgTime,MsgFH_FaultType,MsgFA_State,MsgFA_Code) VALUES (" + vclId + ",'" + fltTime + "',2,1," + kFltCode + ")");
                        }
                    }
                }

            } else {
                //判断kafka获取到的故障集合是否为空
                if (!kfkFltMap.isEmpty()) {
                    //不存在（则将kafka获取的所有故障信息保存）
                    tx.hmset(redisKey, kfkFltMap);
                    //将所有故障信息入库保存（现行故障表，故障月表）
                    for (String fltCode : kfkFltMap.keySet()) {
                        String fltTime = MapUtils.getString(kfkFltMap, fltCode);
                        String FltTableN = fltTime.substring(0, 7).replace("-", "");
                        sqlList.add("INSERT INTO Msg_Flt_Happening(MsgFH_Vcl_ID,MsgFH_MsgTime,MsgFH_FaultType,MsgFH_Code) VALUES (" + vclId + ",'" + fltTime + "',2," + fltCode + ")");
                        sqlList.add("INSERT INTO Msg_FaultAlarm_" + FltTableN + "(MsgFA_Vcl_ID,MsgFA_MsgTime,MsgFH_FaultType,MsgFA_State,MsgFA_Code) VALUES (" + vclId + ",'" + fltTime + "',2,1," + fltCode + ")");
                    }
                }
            }
            //批量执行sql并执行提交redis事物
            tx.exec();
            jedis.close();
            if (sqlList.size() != 0) {
                DruidUtil.batch(sqlList);
            }
        }
        return null;
    }
}
